import { Button, Form, Select } from "antd";
import React from "react";
import { ModalForm } from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { globalConfigV1AdminControllerShow } from "@/services/auto/globalConfigAdmin";
import { csvStrToDataSet, dataSetToCsv, formatNumber, findNearestTargetRow } from "common/utils/utils";
import NP from 'number-precision';
import { useModel } from "@umijs/max";

interface Props{
  onConfirm: (data: string)=>void;
  sourceData: string;
}

export default function GenerateDataModal(props:Props){
  const {onConfirm,sourceData} =  props;

  const [form] = Form.useForm<{
    target: string;
  }>();

  const {data: getGlobalConfigsUniqueData} = useModel('global-config')

  return <>
    <ModalForm
      form={form}
      title="生成数据"
      width={800}
      trigger={
        <Button>生成CFR数据</Button>
      }
      onFinish={(values)=>{
        const targetDataSet = getGlobalConfigsUniqueData!.targets.find(item=>item.name === values.target)!.dataSet;
        const sourceDataSet = csvStrToDataSet(sourceData);

        const newDataSet = [sourceDataSet[0]];

        sourceDataSet.forEach((rows, index)=>{
          if(index !== 0){
            const [xData, ...yAxisDataList] = rows;

            const newDataSetRow = [xData];

            yAxisDataList.forEach(yAxisDataItem=>{
              const targetRows = findNearestTargetRow(targetDataSet, xData);
              /*console.log(formatNumber(xData));
              console.log(formatNumber(yAxisDataItem));
              console.log(formatNumber(targetRows![1])) ;
              console.log( NP.strip(formatNumber(yAxisDataItem) - formatNumber(targetRows![1]))) ;
              console.log('---')*/
              newDataSetRow.push(NP.strip(formatNumber(yAxisDataItem) - formatNumber(targetRows![1])).toString());
            })

            newDataSet.push(newDataSetRow);
          }
        })


        onConfirm(dataSetToCsv(newDataSet));

        return Promise.resolve(true);
      }}
    >
      <Form.Item name="target" rules={[
        {
          required: true,
          message: '请选择'
        }
      ]}>
        <Select options={getGlobalConfigsUniqueData?.targets.map(item=>{
          return {
            label: item.name,
            value: item.name,
          }
        })} />
      </Form.Item>
    </ModalForm>
  </>


}
